import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import router, { resetRouter } from '@/router'

const state = {
  // token: getToken(),
  name: '',
  avatar: '',
  introduction: '',
  roles: []
}

const mutations = {
  // SET_TOKEN: (state, token) => {
  //   state.token = token
  // },
  SET_INTRODUCTION: (state, introduction) => {
    state.introduction = introduction
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_ROLES: (state, roles) => {
    state.roles = roles
  }
}

const actions = {
  // user login
  // 参数一：这里将 context 对象解构了 commit 方法 参数二：登录提交的数据
  async login({ commit }, userInfo) {
    const { username, password } = userInfo // 将 userInfo 表单数据对象解构

    // 调用发送请求的 login 方法，返回的是 Promise 对象
    // username.trim()：去掉 username 的前后空格，并创建对象给 login 方法
    const body = await login({ username: username.trim(), password: password });
    setToken(body.data.token) // 将令牌存到 Cookie
  },

  // get user info 获取用户信息
  async getInfo({ commit, state }) {
    const {data} = await getInfo(getToken()) // 将返回的 body 对象解构
    const { roles, name, avatar, introduction } = data // 将服务器返回的用户详情对象解构
    // 判断角色信息是否缺失
    if (!roles || roles.length <= 0) {
      throw '用户角色不能为空'
    }
    // 把服务器返回的信息存放到 Vuex 中
    commit('SET_ROLES', roles)
    commit('SET_NAME', name)
    commit('SET_AVATAR', avatar)
    commit('SET_INTRODUCTION', introduction)
    // 直接返回角色信息，调用方不用再解构
    return roles
  },

  // user logout
  logout({ commit, state, dispatch }) {
    return new Promise((resolve, reject) => {
      // 从 Cookies 中获取令牌
      logout(getToken()).then(() => {
        // commit('SET_TOKEN', '')
        commit('SET_ROLES', [])
        removeToken()
        resetRouter()

        // reset visited views and cached views
        // to fixed https://github.com/PanJiaChen/vue-element-admin/issues/2485
        dispatch('tagsView/delAllViews', null, { root: true })

        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      // commit('SET_TOKEN', '')
      commit('SET_ROLES', [])
      removeToken()
      resolve()
    })
  },

  // dynamically modify permissions
  async changeRoles({ commit, dispatch }, role) {
    const token = role + '-token'

    // commit('SET_TOKEN', token)
    setToken(token)

    const { roles } = await dispatch('getInfo')

    resetRouter()

    // generate accessible routes map based on roles
    const accessRoutes = await dispatch('permission/generateRoutes', roles, { root: true })
    // dynamically add accessible routes
    router.addRoutes(accessRoutes)

    // reset visited views and cached views
    dispatch('tagsView/delAllViews', null, { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
